import { defineStore } from "pinia";
import { ref } from "vue";
import storage from "~/utils/storage";

interface User {
  id: number;
  name: string;
  username: string;
  nickName: string;
  phone: string;
  goodsUrl: string;
  inviteCode: string;
  headImg: string;
  score: string;
  email: string;
  status: 0 | 1;
  VIPlevel: Number;
  PythonCourseVIP: Boolean;
  departmentId: string;
  teacherId: string;
  createTime: Date;
  [key: string]: any;
}

// 本地缓存
const data = storage.info();

export const useUserStore = defineStore("user", {
  state: function () {
    // 标识
    const token = ref<string>(data.token);

    // 设置标识
    function setToken(data: {
      token: string;
      expire: string;
      refreshToken: string;
      refreshExpire: string;
    }) {
      // 请求的唯一标识
      token.value = data.token;
      storage.set("token", data.token, data.expire);

      // 刷新 token 的唯一标识
      storage.set("refreshToken", data.refreshToken, data.refreshExpire);
    }

    // 刷新标识
    async function refreshToken(): Promise<string> {
      return new Promise((resolve, reject) => {
        // TODO:  实现刷新token
        // service.base.open
        // 	.refreshToken({
        // 		refreshToken: storage.get("refreshToken")
        // 	})
        // 	.then((res) => {
        // 		setToken(res);
        // 		resolve(res.token);
        // 	})
        // 	.catch((err) => {
        // 		logout();
        // 		reject(err);
        // 	});
      });
    }

    // 用户信息
    const info = ref<User | null>(data.userInfo);

    // 设置用户信息
    function set(value: any) {
      info.value = value;
      storage.set("userInfo", value);
    }

    // 清除用户
    function clear() {
      storage.remove("userInfo");
      storage.remove("token");
      token.value = "";
      info.value = null;
    }

    // 退出
    async function logout() {
      clear();
    }

    // 获取用户信息
    async function get() {
      // TODO: 实现C端用户获取用户信息
    }


    return {
      token,
      info,
      get,
      set,
      logout,
      clear,
      setToken,
      refreshToken,
    };
  },
  getters: {
    // 自动将返回类型推断为数字
    isZhuBo(state) {
      return state.info?.id == 2 || state.info?.id == 6;
    },
  },
});
